<template>
  <el-dialog
    v-el-drag-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
    <el-form-item label="活动标题" prop="shareTitle">
      <el-input v-model="dataForm.shareTitle" placeholder="活动标题"></el-input>
    </el-form-item>
    <el-form-item label="活动内容" prop="shareContent">
      <el-input type="textarea" v-model="dataForm.shareContent" placeholder="活动内容"></el-input>
    </el-form-item>
    <el-form-item label="分享点击图片URL" prop="urlImg">
      <el-upload
        :class="{hide:hideUpload}"
        :action="this.$http.adornUrl(`/share/uploadShare?token=${this.$cookie.get('token')}`)"
        :limit="1"
        list-type="picture-card"
        :file-list="dataForm.urlImg"
        :on-preview="handlePreview"
        :on-success="handleSuccess"
        :on-remove="handleRemove"
        :on-exceed="onExceed">
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible" :append-to-body='true'>
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-form-item>
    <el-form-item label="分享微信时的Logo" prop="shareLogo">
      <el-upload
        :class="{hide:hideUpload}"
        :action="this.$http.adornUrl(`/share/uploadShare?token=${this.$cookie.get('token')}`)"
        :limit="1"
        list-type="picture-card"
        :file-list="dataForm.shareLogo"
        :on-preview="handlePreview"
        :on-success="handleSuccess1"
        :on-remove="handleRemove1"
        :on-exceed="onExceed">
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible" :append-to-body='true'>
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-form-item>
    <el-form-item label="活动主图" prop="shareImg">
      <el-upload
        :class="{hide:hideUpload}"
        :action="this.$http.adornUrl(`/share/uploadShare?token=${this.$cookie.get('token')}`)"
        :limit="1"
        list-type="picture-card"
        :file-list="dataForm.shareImg"
        :on-preview="handlePreview"
        :on-success="handleSuccess2"
        :on-remove="handleRemove2"
        :on-exceed="onExceed">
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible" :append-to-body='true'>
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-form-item>
    <el-form-item label="活动二维码" prop="shareQrCode">
      <el-upload
        :class="{hide:hideUpload}"
        :action="this.$http.adornUrl(`/share/uploadShare?token=${this.$cookie.get('token')}`)"
        :limit="1"
        list-type="picture-card"
        :file-list="dataForm.shareQrCode"
        :on-preview="handlePreview"
        :on-success="handleSuccess3"
        :on-remove="handleRemove3"
        :on-exceed="onExceed">
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible" :append-to-body='true'>
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-form-item>
    <el-form-item label="备用消息" prop="backMessage">
      <el-input v-model="dataForm.backMessage" placeholder="备用消息"></el-input>
    </el-form-item>
    <el-form-item label="赠送商品名字" prop="goodsName">
      <el-input v-model="dataForm.goodsName" placeholder="赠送商品名字"></el-input>
    </el-form-item>
    <el-form-item label="推荐人赠送积分数量 " prop="recommendIntegral">
      <el-input v-model="dataForm.recommendIntegral" placeholder="推荐人赠送积分数量 "></el-input>
    </el-form-item>
    <el-form-item label="被推荐人赠送积分" prop="passiveIntegral">
      <el-input v-model="dataForm.passiveIntegral" placeholder="被推荐人赠送积分"></el-input>
    </el-form-item>
    <el-form-item label="活动开始时间" prop="startTime">
      <el-date-picker v-model="dataForm.startTime" placeholder="活动开始时间" @change="startTime()"></el-date-picker>
    </el-form-item>
    <el-form-item label="活动结束时间" prop="endTime">
      <el-date-picker v-model="dataForm.endTime" placeholder="活动结束时间" @change="endTime()"></el-date-picker>
    </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        hideUpload: false,
        limitCount: 1,
        visible: false,
        dialogImageUrl: '',
        dialogVisible: false,
        dataForm: {
          weChatId: 0,
          shareTitle: '',
          shareContent: '',
          urlImg: [],
          shareLogo: [],
          shareImg: [],
          shareQrCode: [],
          backMessage: '',
          goodsName: '',
          recommendIntegral: '',
          passiveIntegral: '',
          startTime: '',
          endTime: '',
          shareState: ''
        },
        dataRule: {
          shareTitle: [
            { required: true, message: '活动标题不能为空', trigger: 'blur' }
          ],
          shareContent: [
            { required: true, message: '活动内容不能为空', trigger: 'blur' }
          ],
          urlImg: [
            { required: true, message: '分享点击图片URL不能为空', trigger: 'blur' }
          ],
          shareLogo: [
            { required: true, message: '分享微信时的Logo不能为空', trigger: 'blur' }
          ],
          shareImg: [
            { required: true, message: '活动主图不能为空', trigger: 'blur' }
          ],
          shareQrcode: [
            { required: true, message: '活动二维码不能为空', trigger: 'blur' }
          ],
          backMessage: [
            { required: true, message: '备用消息不能为空', trigger: 'blur' }
          ],
          goodsName: [
            { required: true, message: '赠送商品名字不能为空', trigger: 'blur' }
          ],
          recommendIntegral: [
            { required: true, message: '推荐人赠送积分数量 不能为空', trigger: 'blur' }
          ],
          passiveIntegral: [
            { required: true, message: '被推荐人赠送积分不能为空', trigger: 'blur' }
          ],
          startTime: [
            { required: true, message: '活动开始时间不能为空', trigger: 'blur' }
          ],
          endTime: [
            { required: true, message: '活动结束时间不能为空', trigger: 'blur' }
          ],
          shareState: [
            { required: true, message: '活动信息状态不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      // 图片预览
      handlePreview (file) {
        // debugger
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      // 文件上传成功的钩子函数
      handleSuccess (res, file, fileList) {
        this.hideUpload = fileList.length >= this.limitCount
        // debugger
        this.$message({
          type: 'info',
          message: '图片上传成功',
          duration: 6000
        })
        if (res.code === 0) {
          this.dataForm.urlImg.push({name: 'tu', url: res.data})
        }
        console.log(this.dataForm.urlImg)
      },
      handleSuccess1 (res, file, fileList) {
        this.hideUpload = fileList.length >= this.limitCount
        // debugger
        this.$message({
          type: 'info',
          message: '图片上传成功',
          duration: 6000
        })
        if (res.code === 0) {
          this.dataForm.shareLogo.push({name: 'tu', url: res.data})
        }
        // console.log(this.dataForm.img)
      },
      handleSuccess2 (res, file, fileList) {
        this.hideUpload = fileList.length >= this.limitCount
        // debugger
        this.$message({
          type: 'info',
          message: '图片上传成功',
          duration: 6000
        })
        if (res.code === 0) {
          this.dataForm.shareImg.push({name: 'tu', url: res.data})
        }
        // console.log(this.dataForm.img)
      },
      handleSuccess3 (res, file, fileList) {
        this.hideUpload = fileList.length >= this.limitCount
        // debugger
        this.$message({
          type: 'info',
          message: '图片上传成功',
          duration: 6000
        })
        if (res.code === 0) {
          this.dataForm.shareQrCode.push({name: 'tu', url: res.data})
        }
        // console.log(this.dataForm.img)
      },
      // 删除文件之前的钩子函数
      handleRemove (file, fileList) {
        this.hideUpload = fileList.length >= this.limitCount
        // debugger
        for (var i = 0; i < this.dataForm.urlImg.length; i++) {
          var picc = this.dataForm.urlImg[i]
          if (picc.url === file.url) {
            this.dataForm.urlImg.splice(i, 1)
          }
        }
        this.$message({
          type: 'info',
          message: '已删除原有图片',
          duration: 6000
        })
      },
      handleRemove1 (file, fileList) {
        this.hideUpload = fileList.length >= this.limitCount
        // debugger
        for (var i = 0; i < this.dataForm.shareLogo.length; i++) {
          var picc = this.dataForm.shareLogo[i]
          if (picc.url === file.url) {
            this.dataForm.shareLogo.splice(i, 1)
          }
        }
        this.$message({
          type: 'info',
          message: '已删除原有图片',
          duration: 6000
        })
      },
      handleRemove2 (file, fileList) {
        this.hideUpload = fileList.length >= this.limitCount
        // debugger
        for (var i = 0; i < this.dataForm.shareImg.length; i++) {
          var picc = this.dataForm.shareImg[i]
          if (picc.url === file.url) {
            this.dataForm.shareImg.splice(i, 1)
          }
        }
        this.$message({
          type: 'info',
          message: '已删除原有图片',
          duration: 6000
        })
      },
      handleRemove3 (file, fileList) {
        this.hideUpload = fileList.length >= this.limitCount
        // debugger
        for (var i = 0; i < this.dataForm.shareQrCode.length; i++) {
          var picc = this.dataForm.shareQrCode[i]
          if (picc.url === file.url) {
            this.dataForm.shareQrCode.splice(i, 1)
          }
        }
        this.$message({
          type: 'info',
          message: '已删除原有图片',
          duration: 6000
        })
      },
      // 上传的文件个数超出设定时触发的函数
      onExceed (files, fileList) {
        this.$message({
          type: 'info',
          message: '最多只能上传1个图片',
          duration: 6000
        })
      },
      init (id) {
        this.hideUpload = false
        this.dataForm.weChatId = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.weChatId) {
            this.$http({
              url: this.$http.adornUrl(`/share/getShareDetailsById/${this.dataForm.weChatId}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.shareTitle = data.data.shareTitle
                this.dataForm.shareContent = data.data.shareContent
                let urlimg1 = 'http://image.yilianbaihui.cn/consumer/wechat/' + data.data.urlImg
                this.dataForm.urlImg.push({name: 'tu', url: urlimg1})
                let shareLogo1 = 'http://image.yilianbaihui.cn/consumer/wechat/' + data.data.shareLogo
                this.dataForm.shareLogo.push({name: 'tu', url: shareLogo1})
                let shareImg1 = 'http://image.yilianbaihui.cn/consumer/wechat/' + data.data.shareImg
                this.dataForm.shareImg.push({name: 'tu', url: shareImg1})
                let shareQrCode1 = 'http://image.yilianbaihui.cn/consumer/wechat/' + data.data.shareQrCode
                this.dataForm.shareQrCode.push({name: 'tu', url: shareQrCode1})
                this.dataForm.backMessage = data.data.backMessage
                this.dataForm.goodsName = data.data.goodsName
                this.dataForm.recommendIntegral = data.data.recommendIntegral
                this.dataForm.passiveIntegral = data.data.passiveIntegral
                this.dataForm.startTime = data.data.startTime
                this.dataForm.endTime = data.data.endTime
              }
              this.hideUpload = true
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/share/${!this.dataForm.weChatId ? 'addShare' : 'modifyShare'}`),
              method: 'post',
              data: this.$http.adornData({
                'weChatId': this.dataForm.weChatId || undefined,
                'shareTitle': this.dataForm.shareTitle,
                'shareContent': this.dataForm.shareContent,
                'urlImg': this.dataForm.urlImg[0].url.substring(this.dataForm.urlImg[0].url.lastIndexOf('/') + 1, this.dataForm.urlImg[0].url.length),
                'shareLogo': this.dataForm.shareLogo[0].url.substring(this.dataForm.shareLogo[0].url.lastIndexOf('/') + 1, this.dataForm.shareLogo[0].url.length),
                'shareImg': this.dataForm.shareImg[0].url.substring(this.dataForm.shareImg[0].url.lastIndexOf('/') + 1, this.dataForm.shareImg[0].url.length),
                'shareQrCode': this.dataForm.shareQrCode[0].url.substring(this.dataForm.shareQrCode[0].url.lastIndexOf('/') + 1, this.dataForm.shareQrCode[0].url.length),
                'backMessage': this.dataForm.backMessage,
                'goodsName': this.dataForm.goodsName,
                'recommendIntegral': this.dataForm.recommendIntegral,
                'passiveIntegral': this.dataForm.passiveIntegral,
                'startTime': this.dataForm.startTime,
                'endTime': this.dataForm.endTime
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      startTime () {
        if (new Date(this.dataForm.startTime).getTime() > new Date(this.dataForm.endTime).getTime()) {
          this.dataForm.startTime = ''
          this.$message({
            showClose: true,
            message: '活动开始时间不得大于活动结束时间',
            type: 'warning'
          })
        }
      },
      endTime () {
        if (new Date(this.dataForm.startTime).getTime() > new Date(this.dataForm.endTime).getTime()) {
          this.dataForm.endTime = ''
          this.$message({
            showClose: true,
            message: '活动开始时间不得大于活动结束时间',
            type: 'warning'
          })
        }
      }
    }
  }
</script>
<style>
  .hide .el-upload--picture-card {  display: none; }
</style>
